package com.siyoumi.app.sys.wxapp;

import com.siyoumi.app.entity.WxUserInfo;
import com.siyoumi.app.sys.service.CommonApiServcie;
import com.siyoumi.app.sys.service.FileHandle;
import com.siyoumi.app.sys.service.WxApiService;
import com.siyoumi.app.sys.service.file.entity.FileUploadData;
import com.siyoumi.app.sys.service.web_oauth.WebOauth;
import com.siyoumi.app.sys.vo.PhoneLoginVo;
import com.siyoumi.app.sys.vo.ScanLoginVo;
import com.siyoumi.app.sys.vo.VaWxUser;
import com.siyoumi.app.sys.vo.VoUploadFile;
import com.siyoumi.component.XRedis;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XFile;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

//小程序通用接口
@Slf4j
@RestController
@RequestMapping("/wxapp/app/api")
public class ApiWxapp
        extends WxAppApiController {

    @PostMapping("/phone_login")
    @Transactional(rollbackFor = Exception.class)
    public XReturn phoneLogin(@Validated PhoneLoginVo data, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        data.setOpenid(getOpenid());
        return WxApiService.getBean().phoneLogin(data);
    }

    /**
     * 扫码确认登陆
     *
     * @param vo
     * @param result
     */
    @PostMapping("/sacn_login")
    public XReturn scanLogin(@Validated ScanLoginVo vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        String val = XRedis.getBean().get(ScanLoginVo.redisKey(vo.getKey()));
        if (XStr.isNullOrEmpty(val)) {
            return EnumSys.ERR_VAL.getR("key已失效");
        }
        if (!"0".equals(val)) {
            return EnumSys.OK.getR("已操作");
        }

        XReturn tokenData = XReturn.getR(0);
        tokenData.setData("timestamp", XDate.toMs());
        tokenData.setData("x", XHttpContext.getX());
        tokenData.setData("uid", getUid());
        tokenData.setData("openid", getOpenid());
        String jwtToken = WxApiService.getBean().getToken(tokenData);
        String webToken = WebOauth.getIns(XHttpContext.getX()).getWebToken(jwtToken);
        //授权成功
        XRedis.getBean().setEx(ScanLoginVo.redisKey(vo.getKey()), webToken, 3 * 60);

        return getR();
    }

    /**
     * 退出登陆
     */
    @PostMapping("/phone_logout")
    public XReturn phoneLogout() {
        return WxApiService.getBean().phoneLogout(getOpenid());
    }

    @GetMapping({"/get_phone", "/getPhone"})
    public XReturn getPhone() {
        String code = input("code");
        return WxApiService.getBean().getPhone(code);
    }


    @PostMapping({"/upload_img"})
    @SneakyThrows
    public XReturn uploadImg(@Validated VoUploadFile vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        List<String> ex = XFile.getImgExtenstions();
        FileUploadData data = FileUploadData.of(vo.getFile0(), ex, SysConfig.getIns().getUploadFileSizeMax(), vo.getSaveFileDir());
        XReturn r = FileHandle.of(vo.getType()).uploadFile(data);
        if (r.ok()) {
            if (vo.getThumbnail() == 1) {
                String fileVal = r.getData("file_val");
                String fullPath = SysConfig.getIns().getUploadPath() + fileVal;
                //图片，并开启缩略图
                XReturn rThumb = CommonApiServcie.getBean().createThumbnailToReturn(new File(fullPath), vo.getThumbnail_width());
                r.setData("thumbnail", rThumb);
            }
        }


        return r;
    }

    @PostMapping({"/upload_file"})
    public XReturn uploadFile(@Validated VoUploadFile vo, BindingResult result) {
        List<String> ex = new ArrayList<>();
        ex.add("xls");
        ex.add("docx");
        ex.add("pdf");
        FileUploadData data = FileUploadData.of(vo.getFile0(), ex, SysConfig.getIns().getUploadFileSizeMax(), vo.getSaveFileDir());

        return FileHandle.of(vo.getType()).uploadFile(data);
    }

    @RequestMapping("/user_edit")
    public XReturn userEdit(WxUserInfo entityWxUserInfo) {
        return WxApiService.getBean().userEdit(entityWxUserInfo);
    }

    @PostMapping("/user_update")
    public XReturn userUpdate(@Validated() VaWxUser vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        return WxApiService.getBean().userUpdate(vo);
    }
}
